package com.example.expandablelistview.cp;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.example.expandablelistview.R;

public class EnglishWordEx extends Activity {
	private WordDBManager mDbManager;
	private SimpleCursorAdapter cursorAdapter;

	private static final String[] columns = {"_id", "eng", "han" };
	private static final int[] to = {R.id.listnum, R.id.listeng, R.id.listhan};
	
	@SuppressWarnings("deprecation")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.englishwordex);
		
		mDbManager = WordDBManager.getInstance(this);
		
		ListView list = (ListView) findViewById(R.id.word_list);		
		
		Cursor cursor = mDbManager.select(columns, null, null, null, null, null);
		startManagingCursor(cursor);
		cursorAdapter = new SimpleCursorAdapter(this, R.layout.list_row, cursor, columns, to,CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		
		list.setAdapter(cursorAdapter);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mDbManager.close();
	}
	
	public void mOnClick(View v) {
		String whereClause=null;
		String[] whereArgs;
		switch (v.getId()) {
			case R.id.insertbtn:
				EditText eng = (EditText) findViewById(R.id.engedit);
				EditText han = (EditText) findViewById(R.id.handedit);
				ContentValues addRowValue = new ContentValues();
				addRowValue.put("eng", eng.getText().toString());
				addRowValue.put("han", han.getText().toString());
				mDbManager.insert(addRowValue);
				eng.setText("");han.setText("");
				break;
			case R.id.selectbtn:
				Cursor cursor = mDbManager.select(columns, null, null, null, null, null);
				cursorAdapter.swapCursor(cursor);
				break;
			case R.id.deletebtn:
				EditText num = (EditText) findViewById(R.id.deledid);
				whereClause = "_id=?";
				whereArgs = new String[1];
				whereArgs[0]=num.getText().toString();
				mDbManager.delete(whereClause, whereArgs);
				num.setText("");
				break;
			case R.id.updatebtn:
				EditText id = (EditText) findViewById(R.id.update_id);
				EditText uphan = (EditText) findViewById(R.id.update_han);
				
				ContentValues updateRowValue = new ContentValues();
				updateRowValue.put("han", uphan.getText().toString());
				
				whereClause = "_id=?";
				whereArgs = new String[1];
				whereArgs[0] = id.getText().toString();
				
				mDbManager.update(updateRowValue, whereClause, whereArgs);
				
				id.setText("");
				uphan.setText("");
				break;
		}
		cursorAdapter.swapCursor(mDbManager.select(columns, null, null, null, null, null));
	}
}
